# -*- coding: utf-8 -*-

import os
import socket

class MySocket:
    _unsend_msg = []
    _event_index = 0
    END_LINE = '\n'
    def __init__(self, host, port):
        self._s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._s.connect((host, port))
        self._buf = ''
    def close(self):
        self._s.close()
    def read_string(self):
        while 1:
            try:
                end_pos = self._buf.find(self.END_LINE)
                if end_pos != -1:
                    end_pos += len(self.END_LINE)
                    msg = self._buf[:end_pos]
                    self._buf = self._buf[end_pos:]
                    return msg
                str = self._s.recv(1024)
                if str == '':
                    raise Exception()
                self._buf = self._buf + str
            except socket.timeout:
                pass
    def read_bytes(self, size):
        while 1:
            try:
                if len(self._buf) >= size:
                    msg = self._buf[:size]
                    self._buf = self._buf[size:]
                    return msg
                str = self._s.recv(1024)
                if str == '':
                    raise Exception()
                self._buf = self._buf + str
            except socket.timeout:
                pass
    def send(self, msg):
        self._s.sendall(msg)
    def send_message(self, control_id, new_value):
        self._unsend_msg.append((control_id, new_value))
    def _send_string(self, msg):
        self._s.sendall(msg + self.END_LINE)
    def do_work_circle(self):
        self._s.setblocking(0)
        while True:
            try:
                if len(self._unsend_msg) > 0:
                    (control_id, new_value) = self._unsend_msg.pop(0)
                    self._send_string('%d %s %d' % (self._event_index, control_id, new_value))
                    self._event_index += 1
                end_pos = self._buf.find(self.END_LINE)
                if end_pos != -1:
                    end_pos += len(self.END_LINE)
                    msg = self._buf[:end_pos]
                    self._buf = self._buf[end_pos:]
                    self._process_msg(msg)
                str = self._s.recv(1024)
                if str == '':
                    return
                self._buf = self._buf + str
            except socket.error:
                pass
    def _process_msg(self, msg):
        print msg

s = MySocket('127.0.0.1', 4242)
print s.read_string()
print s.read_string()
print s.read_string()
print s.read_string()
print s.read_string()
s.send('test_panel\n')
dir_name = '../data/test_panel'
if not os.path.isdir(dir_name):
    os.mkdir(dir_name)
num_files = int(s.read_string())
print 'Number of files: %s' % num_files
for i in range(num_files):
    file_name = s.read_string()
    file_name = file_name[:-len(MySocket.END_LINE)]
    file_size = int(s.read_string())
    print 'File %s (%d bytes)' % (file_name, file_size)
    f = open(os.path.join(dir_name, file_name), 'wb')
    while file_size > 0:
        if file_size >= 1024:
            dose = 1024
        else:
            dose = file_size
        file_size -= dose
        f.write(s.read_bytes(dose))
    f.close()
s.do_work_circle()
s.close()